#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <pthread.h>

const unsigned int size = 1024;
const int SOCK_ERR = 1;

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
};

void* recv_message(void* args)
{
    struct ThreadData* td = static_cast<struct ThreadData*>(args);
    while(true)
    {
        std::string message;

        std::getline(std::cin, message);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (const struct sockaddr*)&td->server, sizeof(td->server));
    }
    return nullptr;
}

void* send_message(void* args)
{
    struct ThreadData* td = static_cast<struct ThreadData*>(args);

    while(true)
    {
        char buffer[size];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t n = recvfrom(td->sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);
        buffer[n] = 0;
        std::cout << buffer << std::endl;
    }
    return nullptr;
}

//程序,ip,port
int main(int argc, char* argv[])
{
    if(argc != 3) exit(-1);
    
    const std::string serverip = argv[1];
    const uint16_t serverport = std::stoi(argv[2]);

    ThreadData td;

    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &td.server.sin_addr);

    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd < 0) exit(SOCK_ERR);


    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    close(td.sockfd);
    return 0;
}